package com.frame.pageform.component;

import java.lang.reflect.Field;
import java.util.*;

import com.frame.database.JdataBean;
import com.frame.util.*;

public class JsonObject extends BaseJsonObject{
    public static final String JSONDATA="jsondata:";
    public static final String HTMLDATA="htmldata:";
    private JsonPage jsonPage;
    private Map map=new HashMap();

    public JsonObject(){

    }

    public void put(String name,Object value){
        map.put(name,value);
    }
    public void putJsonString(String name,String jsonstr){
        map.put(name,new JsonString(jsonstr));
    }
    /**
     * 返回json数据格式
     */
    public String toString(){
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        Iterator iterator=map.entrySet().iterator();
        int i=0;
        while(iterator.hasNext()){
            if(i!=0)
                sb.append(",");
            Map.Entry entry = (Map.Entry)iterator.next();
            Object obj=entry.getValue();
            sb.append(quote(entry.getKey().toString())+":"+objToJson(obj));
            i++;
        }
        if(jsonPage!=null){
            if(jsonPage.getBuffer()!=null){
                if(i!=0)
                    sb.append(",");
                sb.append(quote("jsonpageinfo_")+":");
                sb.append("[");
                sb.append(jsonPage.getBuffer());
                sb.append("]");
                if(jsonPage.isResetForm())
                    sb.append(","+quote("resetForm_")+":"+quote("true"));
            }
        }
        sb.append("}");

        return JSONDATA+sb.toString();
    }
    public String objToJson(Object obj){
        if(obj==null)return quote("");
        StringBuffer sb = new StringBuffer();
        Class c=obj.getClass();
        if(c==String.class || c==Date.class || c==java.sql.Timestamp.class){
            return quote(obj.toString());
        }else if(c==Integer.class || c == int.class || c==Double.class|| c==double.class|| c==Float.class
                || c==float.class || c==Boolean.class || c==boolean.class || c==java.math.BigDecimal.class || c==long.class|| c==Long.class){
            return obj.toString();
        }else if(obj instanceof JdataBean){
            JdataBean beanmap=(JdataBean)obj;
            Object[] keys=beanmap.getDataMap().keySet().toArray();
            sb.append("{");
            for(int b=0;b<keys.length;b++){
                Object obj2=beanmap.get(keys[b].toString());
                if(b!=0)
                    sb.append(",");
                sb.append(quote(keys[b].toString())+":"+objToJson(obj2));
            }
            sb.append("}");
        }else if(obj instanceof Map){
            Map beanmap=(Map)obj;
            Object[] keys=beanmap.keySet().toArray();
            sb.append("{");
            for(int b=0;b<keys.length;b++){
                Object obj2=beanmap.get(keys[b].toString());
                if(b!=0)
                    sb.append(",");
                sb.append(quote(keys[b].toString())+":"+objToJson(obj2));
            }
            sb.append("}");
        }else if(obj instanceof List){
            List list=(List)obj;
            sb.append("[");
            for(int i=0;i<list.size();i++){
                if(i!=0)sb.append(",");
                sb.append(objToJson(list.get(i)));
            }
            sb.append("]");

        }else if(obj instanceof JsonString){
            return obj.toString();
        }else if(obj.getClass().isArray()){
            Object[] objs=(Object[])obj;
            sb.append("[");
            for(int i=0;i<objs.length;i++){
                if(i!=0)sb.append(",");
                sb.append(objToJson(objs[i]));
            }
            sb.append("]");
        }else{
            Field[] field=obj.getClass().getDeclaredFields();
            sb.append("{");
            for(int j=0;j<field.length;j++){
                String name=field[j].getName();
                Object value="";
                try {
                    value=BeanUtils.getValue(obj,name);
                } catch (Exception e) {
                }
                if(j!=0)
                    sb.append(",");
                sb.append(quote(name)+":"+objToJson(value));
            }
            sb.append("}");
        }
        return sb.toString();
    }
    /**
     * 返回页面形式的json数据格式
     * 功能:<br>
     * 参数:<br>
     * 作者:王海锋<br>
     * 时间:2012-3-26 上午09:53:18<br>
     * 说明:<br>
     * 变更:<br>
     */
    public String toPageString(){
        String json=toString();
        return HTMLDATA+"<html>"+json.replace(JSONDATA, "")+"</html>";
    }

    public void setStateCode(int code){
        map.put("stateCode_",code+"");
    }

    /**
     * 将对象转为数组形式的json格式
     * 功能:<br>
     * 参数:<br>
     * 作者:王海锋<br>
     * 时间:2012-3-26 上午09:52:26<br>
     * 说明:<br>
     * 变更:<br>
     */
    @Deprecated
    public String listToJson(List list){
        StringBuffer sb = new StringBuffer();
        if(list!=null){
            for(int i=0;i<list.size();i++){
                Object obj=list.get(i);

                if(i!=0)
                    sb.append(",");
                sb.append("{");
                if(obj.getClass() == String.class){
                    sb.append(quote("value")+":"+quote(obj.toString()));
                }else if(obj instanceof JdataBean){
                    JdataBean beanmap=(JdataBean)obj;
                    Object[] keys=beanmap.getDataMap().keySet().toArray();
                    for(int b=0;b<keys.length;b++){
                        Object obj2=beanmap.get(keys[b].toString());
                        if(b!=0)
                            sb.append(",");
                        sb.append(quote(keys[b].toString())+":"+quote(obj2==null?"":obj2.toString()));
                    }
                }else{
                    Field[] field=obj.getClass().getDeclaredFields();
                    for(int j=0;j<field.length;j++){
                        String name=field[j].getName();
                        Object value="";
                        try {
                            value=BeanUtils.getValue(obj,name);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        if(j!=0)
                            sb.append(",");
                        if(value instanceof java.util.Date){
                            try{
                                value=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((java.util.Date)value);
                            }catch(Exception ew){
                                value=new java.text.SimpleDateFormat("yyyy-MM-dd").format((java.util.Date)value);
                            }
                        }
                        sb.append(quote(name)+":"+quote(value==null?"":value.toString()));
                    }
                }

                sb.append("}");
            }
        }
        return sb.toString();
    }
    public void clear(){
        map.clear();
    }
    public JsonPage getJsonPage() {
        if(jsonPage==null)
            jsonPage=new JsonPage();
        return jsonPage;
    }
    public void setJsonPage(JsonPage jsonPage) {
        this.jsonPage = jsonPage;
    }
    public class JsonPage {
        /**
         * 要输出到页面上的内容
         */
        private StringBuffer buffer;
        private boolean resetForm=false;
        private boolean listFlesh=false;

        public void executeScript(String s){
            println("{"+quote("script_")+":"+quote(s)+"}");
        }
        public void showInfoMsg(String s){
            println("{"+quote("showInfoMsg_")+":"+quote(s)+"}");
        }
        public void showAlertMsg(String s){
            println("{"+quote("showAlertMsg_")+":"+quote(s)+"}");
        }
        public void showErrorMsg(String s){
            println("{"+quote("showErrorMsg_")+":"+quote(s)+"}");
        }

        public void showOkMsg(String s){
            println("{"+quote("showOkMsg_")+":"+quote(s)+"}");
        }
        public void setReturnValue(String s){
            executeScript("$w.setWinReturn("+quote(s)+")");
        }
        public void closeWin(){
            executeScript("$w.closeCurrWin()");
        }
        public void closeWin(String s){
            executeScript("$w.closeCurrWin("+quote(s)+")");
        }
        public void setValue(String name, String value){
            executeScript("$getByName('"+name+"',$w.currWin()).val('"+value+"');");
        }
        private void println(String s)
        {
            if(buffer==null)
                buffer = new StringBuffer();
            if(!"".equals(buffer.toString()))
                buffer.append(",");
            buffer.append(s);
        }
        public StringBuffer getBuffer() {
            return buffer;
        }
        public boolean isResetForm() {
            return resetForm;
        }
        public void setResetForm(boolean resetForm) {
            this.resetForm = resetForm;
        }
        public boolean isListFlesh() {
            return listFlesh;
        }
        public void setListFlesh(boolean listFlesh) {
            this.listFlesh = listFlesh;
            if(listFlesh)
                executeScript("$w.listFlesh=true;");
            else
                executeScript("$w.listFlesh=false;");
        }

    }
}
